package quick.start.core.postq;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import quick.start.core.ApplicationBase;

public abstract class FilePostQ<T extends Task> {
    private static final String DEFAULT_PATH = ApplicationBase.getApplication().getFilesDir().getPath() 
    		+ File.separator + PostQueue.POST_QUEUE + File.separator;

    private String mPath;

    protected FilePostQ() {
        mPath = DEFAULT_PATH + getClass().getSimpleName();
    }

    protected FilePostQ(String path) {
        this(path, false);
    }

    protected FilePostQ(String path, boolean afterBasePath) {
        mPath = (afterBasePath ? DEFAULT_PATH : "") + path;
    }

    public String getPath() {
        return mPath;
    }

    public void loop() {
        File[] files = onPrepare();

        if(null == files) return;
        for (File file : files) {
            T task = genTask(file);
            if (task != null && task.doTask()) file.delete();
        }
    }

    public boolean post(T task) {
        return post(task, mPath);
    }

    public final boolean post(T task, String path) {
        try {
            FileUtils.forceMkdir(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return saveTask(task);
    }

    protected File[] onPrepare() {
        return new File(mPath).listFiles();
    }

    protected abstract boolean saveTask(T task);

    protected abstract T genTask(File file);

    public int size() {
        File file = new File(mPath);
        if (!file.exists()) return 0;

        return file.list().length;
    }
}
